import {Component, OnInit} from '@angular/core';
import {Router} from '@angular/router';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {interval} from 'rxjs';

import {SendEmail} from '../../globalEnums/send-email.enum';
import {EmailService} from '../../service/email.service';
import {UserService} from '../../service/user.service';
import {Md5} from 'ts-md5';

@Component({
  selector: 'app-forget-password',
  templateUrl: './forget-password.component.html',
  styleUrls: ['./forget-password.component.css']
})
export class ForgetPasswordComponent implements OnInit {
  msg: string; // 全局提示信息
  second = 30; // 倒计时等待时间,单位秒
  waitSeconds = 0;
  // 表单
  itemForForm: FormGroup = null; // 表单对象
  formBtnDisabled = false; // 默认激活表单提交,true禁用表单提交
  formValidSuccess = true; // 默认成功样式
  placeholder = { // 表单字段说明
    receiver: {'title': '邮箱', 'prompt': 'you@example.com'},
    code: {'title': '验证码', 'prompt': '8888'},
    pass: {'title': '新密码', 'prompt': '字母开头,长度在6~10之间,只能包含字母、数字和下划线'},
    rePass: {'title': '重复新密码', 'prompt': '字母开头,长度在6~10之间,只能包含字母、数字和下划线'},
  };

  /**
   * 构造函数
   */
  constructor(
    private router: Router,
    private emailService: EmailService,
    private formBuilder: FormBuilder,
    private userService: UserService) {
    this.createItemForForm(); // 创建表单对象
  }

  /**
   *  初始化函数
   */
  ngOnInit() {
  }

  /**
   * 创建表单
   */
  createItemForForm() {
    this.itemForForm = this.formBuilder.group({
      receiver: [null, [
        Validators.required,
        Validators.pattern('^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$')]
      ],
      code: [null, [
        Validators.required,
        Validators.pattern('^[A-Za-z0-9]{4}$')]],
      pass: [null, [
        Validators.required,
        Validators.pattern('^[a-zA-Z]\\w{5,9}$')]
      ],
      rePass: [null, [
        Validators.required,
        Validators.pattern('^[a-zA-Z]\\w{5,9}$')]
      ]
    });
  }

  /**
   * 获取验证码
   */
  onSentEmail(): void {
    this.msg = null;
    const secondsCounter = interval(1000).subscribe(n => {
      this.waitSeconds = this.second - n;
      if (this.waitSeconds === 0) {
        secondsCounter.unsubscribe();
      }
    });
    this.itemForForm.value.category = SendEmail.GET_PASSWORD; // 设置邮件的类型
    this.emailService.sendEmail(this.itemForForm.value).subscribe(responseJson => {
      if (responseJson.code === 0) {
        this.msg = '验证码发送成功!';
        this.formBtnDisabled = false; // 激活表单提交
        this.formValidSuccess = true; // 成功样式
      } else {
        this.msg = responseJson.msg;
        this.formBtnDisabled = true; // 屏蔽表单提交
        this.formValidSuccess = false; // 失败样式
      }
    });
  }

  /**
   *  提交表单
   * @param userForm
   */
  onSubmit(itemForForm): void {
    this.formBtnDisabled = true; // 禁用表单提交
    if (this.itemForForm.value.pass === this.itemForForm.value.rePass) {
      this.itemForForm.value.category = SendEmail.GET_PASSWORD; // 设置邮件的类型
      this.itemForForm.value.password = Md5.hashStr(this.itemForForm.value.pass).toString();
      sessionStorage.setItem('password', this.itemForForm.value.pass);
      this.itemForForm.value.pass = 'abc12345';
      this.itemForForm.value.rePass = 'abc12345';
      this.userService.modifyPassword(this.itemForForm.value).subscribe(responseJson => {
        if (responseJson.code === 0) {
          /*
            操作成功
           */
          sessionStorage.clear();
          setTimeout(() => {
            this.router.navigateByUrl('/login');
          }, 500);
        } else {
          /*
            操作失败
           */
          this.formBtnDisabled = false; // 激活表单提交
          this.formValidSuccess = false; // 失败样式
          this.msg = responseJson.msg;
          this.itemForForm.value.pass = sessionStorage.getItem('password');
          this.itemForForm.value.rePass = sessionStorage.getItem('password');
        }
      });
    } else {
      this.formBtnDisabled = false; // 开启表单提交
      this.formValidSuccess = false; // 失败样式
      this.msg = '密码不一致!';
    }
  }

}
